package com.luis.toolsuite.controller;

import com.luis.toolsuite.kmeans.Kmeans;
import com.luis.toolsuite.kmeans.model.Cluster;
import com.luis.toolsuite.service.KmeansDataRepository;
import com.luis.toolsuite.util.KMeansUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
public class KMeansController {

	@Autowired
	private KmeansDataRepository dataService;

	@RequestMapping("/kmeans/data")
	@ResponseBody
	public Map<String,Object> data(@RequestParam("k")int k) {
		Map<String,Object> resultMap = new LinkedHashMap<>();
		List<Double[]> dataset = KMeansUtil.convertObjectToPoint(dataService.findAll());
		Kmeans kmeans = new Kmeans(k,1,dataset);
		kmeans.train();
		//讲kmeans对象转换成Map格式
		Map<String,List<Double[]>> dataMap = convertFromKmeans(kmeans);
		//添加质心
		dataMap.put("Center",kmeans.getCenterList());
		resultMap.put("data",dataMap);
		resultMap.put("sse",kmeans.getTotalSSE());
		resultMap.put("iteration",kmeans.getCurrentIteration());
		resultMap.put("total",dataset.size());
		return resultMap;
	}

	private Map<String,List<Double[]>> convertFromKmeans(Kmeans k){
		Map<String,List<Double[]>> resultMap = new LinkedHashMap<>();
		int i =1;
		for(Cluster c :k.getClusterList()){
			resultMap.put("Cluster"+(i++), c.getPointList());
		}
		return resultMap;
	}
}
